<template>
  <div>
    <h3 class="title">颁奖</h3>
    <!-- {{ resList.imgUrl }} -->
    <el-row>
      <el-col :span="24">
        <el-form
          v-loading="loading"
          ref="ruleForm"
          :name="resList"
          :model="resList"
          :rules="rules"
          element-loading-text="颁奖中请稍后..."
          label-width="120px"
          class="demo-ruleForm"
          style="margin-top: 20px;">
          <!-- {{ resList }} -->
          <el-form-item :prop="'manageId'" label="选择报名入口">
            <el-col :span="18" >
              <el-select v-model="resList.manageId" @change="chooseName()">
                <el-option v-for="item in names" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item :class="'add_tip'" :prop="'excel'" label="导入文件">
            <el-upload
              :action="action"
              :multiple="false"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :http-request="uploadExcel"
              style="float:left"
              accept=".xls,.xlsx"
            >
              <el-button type="primary" size="small">选择Excel文件</el-button>
            </el-upload>
            <span style="margin-left:10px; color:#666">{{ excelName }}</span>
          </el-form-item>
          <el-form-item :class="'add_tip'" :prop="'cost'" label="上传奖状">
            <el-col :span="24" >
              <div style="width:240px" class="fl">
                <div class="thumbnail">
                  <img v-show="resList.imgUrl" :src="resList.imgUrl" alt="">
                </div>
                <div class="uploadBox">
                  <el-upload
                    :data="upLoadData"
                    :before-upload="beforeAvatarUpload"
                    :on-success="handleAvatarSuccess"
                    action="https://up-z1.qiniup.com">
                    <el-button
                      type="primary"
                      size="small"
                    >选择图片</el-button>
                  </el-upload>
                  <el-button v-show="resList.imgUrl" class="btn_clear fr" size="small" type="info" @click="clearPic()">清除</el-button>
                </div>
                <p style="color:#F56C6C;">请上传537x759像素的图片</p>
              </div>
            </el-col>

          </el-form-item>
          <el-form-item label="奖状编号规则"/>
          <!-- <el-form-item :class="'add_tip'" label="奖状编号规则"> -->
          <el-form-item prop="preEn" label="英文">
            <el-col :span="8" >
              <el-input v-model="resList.preEn"/>
            </el-col>
          </el-form-item>
          <el-form-item prop="preNum" label="数字" style="margin-top:30px">
            <el-col :span="8" >
              <el-input v-model="resList.preNum" type="number"/>
            </el-col>
          </el-form-item>
          <!-- </el-form-item> -->
          <el-form-item style="margin-top:40px;">
            <el-button v-preventReClick type="primary" @click="submitForm('ruleForm')">确定</el-button>
            <el-button v-preventReClick @click="$router.go(-1)">关闭</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <!-- <el-col :span="12">
        这里是导入的表格
      </el-col> -->
    </el-row>

  </div>
</template>
<script>
import { getRegistryList, registryAward } from '@/api/registry'
import { Message } from 'element-ui'
import { GetQiniuToken } from '@/utils/qiniuUpload.js'

export default {
  data() {
    return {
      action: '',
      excelName: '',
      resList: {
        manageName: '',
        manageId: '',
        preEn: '',
        preNum: '',
        imgUrl: 'http://ht.ma3u.com/FvPOuHuQ94c10GqW1y5gGbIrYqT1',
        excelFile: null
      },
      listQuery: {
        pageNum: 0,
        pageSize: 1000,
        status: 1
      },
      rules: {
        manageId: [
          { required: true, message: '请选择报名入口', trigger: 'blur' }
        ],
        preEn: [
          { required: true, message: '请输入英文编号', trigger: 'blur' },
          { pattern: /^[A-Za-z]+$/, message: '只能输入英文', trigger: 'blur' }
        ],
        preNum: [
          { required: true, message: '请输入数字', trigger: 'blur' },
          { pattern: /^[1-9]\d*$/, message: '第一个数字不能为零', trigger: 'blur' }
        ]
      },
      names: [],
      upLoadData: {
        token: '',
        keyname: ''
      },
      loading: false
    }
  },
  created() {
    this.getRegistryName()
    this.getToken()
  },
  methods: {
    chooseName() {
      this.names.forEach(item => {
        // console.log(item.id, '===', this.resList.manageId)
        if (item.id === this.resList.manageId) {
          this.resList.manageName = item.name
        }
      })
      this.$refs['ruleForm'].clearValidate(['manageId'])
    },
    handleAvatarSuccess(res, file) {
      console.log('res:', res)
      console.log('file:', file)
      this.resList.imgUrl = 'http://ht.ma3u.com/' + res.key
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 10MB!');
      }
      const fileType = file.type.split('/')[1]
      this.upLoadData.keyname = `${new Date().getTime()}${Math.random().toString(36).slice(2)}.${fileType}`
      return isJPG && isLt2M;
    },
    getToken() {
      this.upLoadData.token = GetQiniuToken().uploadToken
    },
    clearPic() {
      this.resList.imgUrl = ''
    },
    // 提交批量上传题目的excel表格
    uploadExcel(file) {
      console.log(file)
      this.resList.excelFile = file.file
      this.excelName = file.file.name
    },
    beforeUpload(file) {
      console.log('before upload');
      console.log(file);
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1);
      const size = file.size / 1024 / 1024;
      if (extension !== 'xlsx') {
        this.$message.warning('只能上传后缀是.xlsx的文件');
      }
      if (size > 10) {
        this.$message.warning('文件大小不得超过10M');
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (!this.resList.excelFile) {
            Message.error('请导入文件')
            return
          }
          if (!this.resList.imgUrl) {
            Message.error('请上传奖状')
            return
          }
          this.loading = true
          const form = new FormData();
          form.append('manageName', this.resList.manageName)
          form.append('manageId', this.resList.manageId)
          form.append('preEn', this.resList.preEn)
          form.append('preNum', this.resList.preNum)
          form.append('imgUrl', this.resList.imgUrl)
          form.append('excelFile', this.resList.excelFile)

          registryAward(form).then(res => {
            if (res.code === '200') {
              this.loading = false
              this.$router.go(-1)
              console.log(res)
            } else {
              Message.error(res.message + '-' + res.data)
            }
          })
        }
      })
    },
    getRegistryName() {
      getRegistryList(this.listQuery).then(res => {
        console.log('报名管理入口名称', res)
        if (res.code === '200') {
          res.data.list.forEach(item => {
            const obj = {
              id: item.id,
              name: item.name
            }
            this.names.push(obj)
          })
        } else {
          Message.error(res.message + '-' + res.data)
        }
      })
    }
  }
}
</script>
<style>
.el-upload-list{
    display: none;
}
.thumbnail{
        padding: 10px;
        width: 240px;
        height: 320px;
        border: 1px solid #eee;
        border-radius: 5px;
        display: flex;
    }
    .thumbnail img{
        width: 100%;
        height: 100%;
    }
    .uploadBox{
        width: 100%;
        position: relative;
    }
    .btn_clear{
        position: absolute;
        bottom: 0;
        right: 0;
        padding: 10px 30px;
    }
.title{
    margin-left:20px
}
</style>
